﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Noea.Graph;
using System.Xml;

namespace Noea.Utils
{
	public static class XmlCreator
	{
		public static XmlDocument getXML(BasicGraph graph, string rootName)
		{
			XmlDocument xmlDoc = new XmlDocument();
			XmlDeclaration decl = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
			xmlDoc.AppendChild(decl);
			XmlProcessingInstruction PI;
			PI = xmlDoc.CreateProcessingInstruction("xml-stylesheet",
				"type='text/xsl' href='style.xsl'");
			xmlDoc.AppendChild(PI);
			XmlElement sitemapXE = xmlDoc.CreateElement("SiteMap");
			xmlDoc.AppendChild(sitemapXE);
			if (graph.Vertices.Count == 0)
				return xmlDoc;

			Vertex rootVertex = graph.Vertices[rootName];
			List<Edge> allEdges = graph.Edges;

			addChilds(rootVertex, ref allEdges, ref sitemapXE, ref xmlDoc);
			//xmlDoc.Save("test.xml");
			return xmlDoc;
		}

		private static void addChilds(Vertex rootVertex, 
			ref List<Edge> allEdges, ref XmlElement xmlRootEl, 
			ref XmlDocument xmlDoc)
		{
			XmlElement xmlChildEl = xmlDoc.CreateElement("Vertex");
			xmlChildEl.SetAttribute("url", rootVertex.Name);
			
			IList<Edge> edges = rootVertex.Edges();
			foreach (Edge edge in edges)
			{
				if (!allEdges.Contains(edge))
					continue;
				allEdges.Remove(edge);
				addChilds(edge.To, ref allEdges, ref xmlChildEl, ref xmlDoc);
			}

			xmlRootEl.AppendChild(xmlChildEl);
		}
	}
}
